#include "GullEngine.h"
#include <iostream>



using namespace std;
using namespace gull::core;

SceneManager* GullEngine::s_gullSceneManager = NULL;
ApplicationManager* GullEngine::s_gullApplicationManager = NULL;
GraphicsManager* GullEngine::s_gullGraphicsManager = NULL;
InputManager* GullEngine::s_gullInputManager = NULL;

GullEngine* gull::core::theGullEngine = NULL;
ApplicationManager* gull::core::theGullApplicationManager = NULL;
GraphicsManager* gull::core::theGullGraphicsManager = NULL;
SceneManager* gull::core::theGullSceneManager = NULL;
InputManager* gull::core::theGullInputManager = NULL;

GullEngine::GullEngine()
{
#if DEBUG
	cout << "############### Welcome in Gull Engine ###############" << endl;
#endif
	theGullApplicationManager = s_gullApplicationManager = ApplicationManager::getInstance();
	theGullSceneManager = s_gullSceneManager = SceneManager::getInstance();
	theGullGraphicsManager = s_gullGraphicsManager = GraphicsManager::getInstance();
	theGullInputManager = s_gullInputManager = InputManager::getInstance();
	theGullEngine = this;
	
#if DEBUG
	cout << "######################################################\n" << endl;
#endif
}

GullEngine::~GullEngine()
{
#if DEBUG
	cout << "\n############## Gull Engine says GoodBye ##############" << endl;
#endif
	
	
	s_gullSceneManager->releaseInstance();
	s_gullApplicationManager->releaseInstance();
	s_gullGraphicsManager->releaseInstance();
	s_gullInputManager->releaseInstance();
	
	
#if DEBUG
	cout << "######################################################\n" << endl;
#endif
}

unsigned int
GullEngine::start()
{
	if(theGullGraphicsManager->getGUIAPI())
		theGullGraphicsManager->getGUIAPI()->startLoop();
	return kExitSuccess;
}

void
GullEngine::reshape(int w, int h)
{
	theGullGraphicsManager->reshapeFrame(w,h);
	theGullApplicationManager->getCurrentApplication()->reshape(w,h);
}

void
GullEngine::mainLoop()
{
	const GullApplication* ga = s_gullApplicationManager->getCurrentApplication();
	if(ga)
	{
		theGullGraphicsManager->refreshFrame();
        theGullApplicationManager->applicationLoop();
        theGullSceneManager->renderScene();
		s_gullGraphicsManager->getGUIAPI()->refresh();
	}
}

void
GullEngine::stop()
{
	delete s_gullApplicationManager->getCurrentApplication();
}
